package com.rzgeo.wcgallay.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.esri.arcgisruntime.geometry.SpatialReference;
import com.rzgeo.wcgallay.comp.WcmValueTxv;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import static android.content.ContentValues.TAG;
import static android.view.accessibility.AccessibilityEvent.INVALID_POSITION;
import static android.widget.AbsListView.CHOICE_MODE_SINGLE;

/**
 * Created by zhanghang on 2017/11/29.
 */

public class WcmUtil {


    public static class Files {
        public static File join(File parent, String name) {
                return new File(parent.getAbsolutePath() + java.io.File.separator + name);
        }

        /**
         * http://blog.csdn.net/y353027520dx/article/details/51535844
         * 复制asset文件到指定目录
         * @param oldPath  asset下的路径
         * @param newPath  SD卡下保存路径
         */
        public static boolean CopyAssets(Context context, String oldPath, String newPath) {
            try {
                String fileNames[] = context.getAssets().list(oldPath);// 获取assets目录下的所有文件及目录名
                if (fileNames.length > 0) {// 如果是目录
                    File file = new File(newPath);
                    file.mkdirs();// 如果文件夹不存在，则递归
                    for (String fileName : fileNames) {
                        CopyAssets(context, oldPath + "/" + fileName, newPath + "/" + fileName);
                    }
                    return true;
                } else {// 如果是文件
                    InputStream is = context.getAssets().open(oldPath);
                    FileOutputStream fos = new FileOutputStream(new File(newPath));
                    byte[] buffer = new byte[1024];
                    int byteCount = 0;
                    while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                        // buffer字节
                        fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                    }
                    fos.flush();// 刷新缓冲区
                    is.close();
                    fos.close();
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    public static class Tip {
        public static String Toast(String msg) {

            Toast.makeText(WcmEnv.getDefaultInst().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            msg = String.format("-=Cgo==Warn=-,提示： %s\n:", msg);
            android.util.Log.i(TAG, msg);
            return msg;
        }

        public static void Alert(String msg) {
            new AlertDialog
                    .Builder(WcmEnv.getDefaultInst().getApplicationContext())
                    .setTitle("注意")
                    .setMessage(msg)
                    .show();
        }
    }

    public final static boolean isValid(String str) {
        return (str != null) && (str.replaceAll("\\s", "").length() > 0);
    }

    public static class SR {
        public static final SpatialReference defaultGeoSR=SpatialReference.create(4326);
        public static final SpatialReference defaultPrjSR=SpatialReference.create(3857);
    }

    public static class Log {

        /***
         * 向开发者输出信息
         * @param msg
         * @return
         */
        public static String Msg(String msg) {
            msg = String.format(">>Wcm:Warn<<,提示： %s\n:", msg);
            android.util.Log.i(TAG, msg);
            return msg;
        }
    }

    public static class Convert {
        public static float Float(Object var) {
            if (var != null) {
                if (var instanceof Long)
                    return ((Long) var).floatValue();
                if (var instanceof Integer)
                    return ((Integer) var).floatValue();
                if (var instanceof Float)
                    return ((Float) var).floatValue();
                if (var instanceof Double)
                    return ((Double) var).floatValue();
                if (var instanceof String)
                    return Float.valueOf(((String) var));
                else
                    return 0.0f;
            } else
                return 0;
        }
    }

    public static class Dialog {

        public interface OnChoice {
            void onResult(boolean confirm);
        }
        public interface OnFinish {
            void onFinish();
        }


        public static void Choice(final Context actvContext, String msg, final OnChoice onChoice) {
            new android.support.v7.app.AlertDialog.Builder(actvContext).setTitle("搜索")
                    .setIcon(android.R.drawable.ic_menu_edit)
                    .setMessage(msg)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if(onChoice!=null)
                                onChoice.onResult(true);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if(onChoice!=null)
                                onChoice.onResult(false);
                        }
                    })
                    .show();
        }


        public static void ShowMsg(final Context actvContext, String msg,final OnFinish onFinish) {
            new android.support.v7.app.AlertDialog.Builder(actvContext).setTitle("搜索")
                    .setIcon(android.R.drawable.ic_menu_edit)
                    .setMessage(msg)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if(onFinish!=null)
                                onFinish.onFinish();
                        }
                    })
                    .show();
        }

        public interface OnList {
            void onConfirm(int select);

            void onCancel();

            void onNeutral();
        }

        public static void List(final Context context, String title, ArrayList<String> items, String neutralButtonTitle, int defSelect, final OnList onList) {

            if(items==null)
                return;

            final ListView listView = new ListView(context);

            listView.setMinimumWidth(800);
            listView.setMinimumHeight(600);
            listView.setAdapter(
                    new ArrayAdapter<>(
                            context, android.R.layout.simple_list_item_single_choice, items.toArray(new String[0])));
            listView.setItemsCanFocus(false);
            listView.setChoiceMode(CHOICE_MODE_SINGLE);


            final int[] _lastSelect = {INVALID_POSITION};
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    listView.setItemChecked(position, true);
                    listView.setSelection(position);
                    _lastSelect[0] = position;
                }
            });


            android.support.v7.app.AlertDialog.Builder dlg =
                    new android.support.v7.app.AlertDialog.Builder(context)
                            .setIcon(android.R.drawable.ic_menu_edit)
                            .setView(listView)
                            .setTitle(title)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (_lastSelect[0] != INVALID_POSITION) {
                                        onList.onConfirm(_lastSelect[0]);
                                    } else {
                                        Tip.Toast( "您必须先选中一个内容");
                                        onList.onCancel();
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    onList.onCancel();
                                }
                            });

            if(WcmUtil.isValid(neutralButtonTitle)){

                dlg.setNeutralButton(neutralButtonTitle, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onList.onNeutral();
                    }
                });
            }

            dlg.show();
        }
    }

    public static class Const {
        public static WcmValueTxv.Unit[] VolumeUtils=new WcmValueTxv.Unit[]{
                new WcmValueTxv.Unit("方",1),
                new WcmValueTxv.Unit("万方",10000),
                new WcmValueTxv.Unit("亿方",100000000),
                new WcmValueTxv.Unit("立方千米",1000*1000*1000)
        };

        public static WcmValueTxv.Unit[] AreaUtils=new WcmValueTxv.Unit[]{
                new WcmValueTxv.Unit("平方米",1),
                new WcmValueTxv.Unit("亩",2000/3),
                new WcmValueTxv.Unit("公顷",10000),
                new WcmValueTxv.Unit("平方千米",1000*1000)
        };
    }
}
